package com.forestar.xzk.commonlibrary;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

/**
 * created by  xzk
 * 2020/7/9   19:02
 * 说明:  定位工具  注意要配合权限申请工具使用
 *      注意填写权限
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 <uses-permission android:name="android.permission.INTERNET" />
 */
public class GpsUtils {
    private LocationManager pLocationManager;
    private String locateType;
    private boolean isGpsEnabled;
    private static final String GPS_LOCATION_NAME = LocationManager.GPS_PROVIDER;
    private GpsListener gpsListener;

    //30s查看是否保存了结果
    private int divideTime = 15_000;
    private double[] doubles ;
    private boolean hasLocationed=false;

    //保存一个最新的gps数据，，延迟半分钟之后，切换为network

    public void setGpsListener(GpsListener gpsListener) {
        this.gpsListener = gpsListener;
    }

    public void getGps(Activity context, View view){
        //获取定位服务
        pLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //判断是否开启GPS定位功能
        isGpsEnabled = pLocationManager.isProviderEnabled(GPS_LOCATION_NAME);
        //定位类型：GPS
        locateType = LocationManager.GPS_PROVIDER;
        //开启定位
        getLocation();

        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                //15s后，切换到网络定位
                Log.d("tag","时间到");
                if(hasLocationed){
                    return;
                }
                Log.d("tag","切换到网络方式定位");
                locateType = LocationManager.NETWORK_PROVIDER;
                getLocation();
            }
        } ,divideTime);

    }

    @SuppressLint("MissingPermission")
    public void stopGps(){
//        pLocationManager.requestLocationUpdates("",0,0,locationListener);
    }

    @SuppressLint("MissingPermission")
    private void getLocation() {
        Location location = pLocationManager.getLastKnownLocation(locateType); // 通过GPS获取位置
        if(null != gpsListener){
            gpsListener.onGpsLocaion(location);
        }

        // 设置监听*器，自动更新的最小时间为间隔N秒(1秒为1*1000，这样写主要为了方便)或最小位移变化超过N米
        try{
            pLocationManager.requestLocationUpdates(locateType, 3000,1,
                    locationListener);
        }catch (IllegalArgumentException e){
            Log.e("定位异常",e.getMessage());
        }
    }

//        获取定位结果:Location[gps 40******,116****** acc=1 et=+29m59s531ms alt=68.859619140625 vel=0.21206827 bear=180.52165 mock]
//    private GPSPanel.LocationBean buildLisdtenerBean(Location location){
//        Log.d(TAG,"获取定位结果:"+location);
//        GPSPanel.LocationBean locationBean = new GPSPanel.LocationBean();
//        locationBean.setSatellitePrecision(location.getAccuracy());
//        locationBean.setGpsLocation(location.getLongitude(),location.getLatitude());
//        //保存定位结果
//        doubles = new double[2];
//        doubles[0] = location.getLongitude();
//        doubles[1] = location.getLatitude();
//
//        hasLocationed=true;
//
//        locationBean.setElevation(location.getAltitude());
//        locationBean.setSatelliteSize(3);
//        locationBean.setTime(DateUtils.longTimeFormatString(location.getTime(),DateUtils.DATE_FORMAT_1));
//
//        locationBean.setCoordinateSystemName("获取中...");
//
//        locationBean.setSaveLocation(location.getLongitude(),location.getLatitude());
//        return locationBean;
//    }

    private LocationListener locationListener = new LocationListener() {
        /**
         * 位置信息变化时触发:当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
         * @param location
         */
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                if(null != gpsListener){
                    gpsListener.onGpsLocaion(location);
                }
            }
        }

        /**
         * GPS状态变化时触发:Provider被disable时触发此函数，比如GPS被关闭
         * @param provider
         * @param status
         * @param extras
         */
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            if(null != gpsListener){
                gpsListener.onGpsStatusChange(provider, status, extras);
            }
//            switch (status) {
//                //GPS状态为可见时
//                case LocationProvider.AVAILABLE:
//                    Toast.makeText(MyApplication.getInstance(), " 当前GPS状态为可见状态", Toast.LENGTH_SHORT).show();
//                    break;
//                //GPS状态为服务区外时
//                case LocationProvider.OUT_OF_SERVICE:
//                    Toast.makeText(MyApplication.getInstance(), " 当前GPS状态为服务区外状态", Toast.LENGTH_SHORT).show();
//                    break;
//                //GPS状态为暂停服务时
//                case LocationProvider.TEMPORARILY_UNAVAILABLE:
//                    Toast.makeText(MyApplication.getInstance(), " 当前GPS状态为暂停服务状态", Toast.LENGTH_SHORT).show();
//                    break;
//            }
        }

        /**
         * 方法描述：GPS开启时触发
         * @param provider
         */
        @Override
        public void onProviderEnabled(String provider) {
            getLocation();
        }

        /**
         * 方法描述： GPS禁用时触发
         * @param provider
         */
        @Override
        public void onProviderDisabled(String provider) {
            ToastUtil.showLong( "请打开gps位置信息功能！");
        }
    };


}
